package cn.hairui.blog.controller;

import cn.hairui.blog.constant.PubConstant;
import cn.hairui.blog.model.Book;
import cn.hairui.blog.model.WebInfo;
import cn.hairui.blog.service.BookService;
import cn.hairui.blog.service.WebInfoService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * <h2>请添加说明
 * </h2>
 * <ol>请添加详细说明
 * </ol>
 *
 * <h2>修改历史
 * </h2>
 * <ol>如有修改，请添加修改历史
 * </ol>
 *
 * </p>
 *
 * @author laoganbu
 * @version V1.0
 * @date 2019/8/13 17:08
 */
@Controller
public class BookController {
    @Autowired
    private WebInfoService webInfoService;
    @Autowired
    private BookService bookService;

    @RequestMapping(value = "/book")

    public String book(HttpServletRequest request, Model model) {
        WebInfo webInfo = webInfoService.find(PubConstant.MY_INFO_ID);
        model.addAttribute("webinfo", webInfo);
        int pageSize = 12;

        Integer pageNum = null;
        String pageNumStr = request.getParameter("pageIndex");
        if (pageNumStr != null) {
            pageNum = Integer.parseInt(pageNumStr);
        }

        if (pageNum == null) {
            pageNum = 1;
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Book> books = bookService.list();
        PageInfo<Book> pageInfo = new PageInfo<Book>(books);
        model.addAttribute("books", books);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("pageIndex", pageNum);
        model.addAttribute("pageSize", pageSize);
        return "book";
    }

    @RequestMapping(value = "/read")
    public String readbook(String id, Model model) {
        WebInfo webInfo = webInfoService.find(PubConstant.MY_INFO_ID);
        model.addAttribute("webinfo", webInfo);
        if (id != null && !"null".equals(id)) {
            try {
                int idNo = Integer.parseInt(id);
                Book book = bookService.find(idNo);
                model.addAttribute("book", book);
                String bookType = "pdf";
                if ("pdf".equals(bookType)) {
                    return "pdfview";
                } else {
                    return "chmview";
                }
            } catch (Exception e) {
                e.printStackTrace();
                return "404";
            }

        } else {
            return "404";
        }
    }
}
